<?php

class Router {

    protected $params ;
    protected $gets ;

    protected $controller = array() ;
    protected $view = array() ;
    protected $model = array() ;

    public function __construct() {

        // Get the url and get from the uri
        $url = explode("\?", $_SERVER['REQUEST_URI']) ;
        
        // Check the first part of url and split them in an array
        $this->params = explode("/", trim($url[0], "/")) ;

        // Check the second part of the url and write it to get
         if(isset($url[1])) {
            $this->gets = explode("&", $url[1]) ;
            foreach($this->gets as $key => $get) {
                $_GET[$key] = $get ;
            
            }
         }
    }

    public function loadController($name = "") {

        // if you have no params 0 or if params 0 is index.php
        if ($name !== "") {
            $this->params[0] = $name ;
            $landingPage = "controllers".DS.$name."Controller.php" ;
        } else if(!$this->params[0] || $this->params[0] == "index.php") {
            $this->params[0] = "index" ;
            $landingPage = "controllers".DS."indexController.php" ;
        } else {
            $landingPage = "controllers".DS.$this->params[0]."Controller.php" ;
        }

        if(file_exists(ROOT . DS . "application" . DS . $landingPage)) {
            require_once(ROOT . DS . "application" . DS . $landingPage) ;

            $controllerName = $this->params[0]."Controller" ;
            $this->controller[$this->params[0]] = new $controllerName() ;

            if(!$name) {
                if(isset($this->params[1]) && method_exists($controller, $this->params[1])) {
                    $this->controller[$this->params[0]]->{$this->params[1]}() ;
                } else {
                    $this->controller[$this->params[0]]->index() ;
                }
            } 

        } else {
            throw new Exception("Controller $landingPage not found") ;
        }

    }

    public function loadView($view, $name = "") {
        if(file_exists(ROOT . DS . "application" . DS . "views" . DS . $view ."View.php")) {
            require_once(ROOT . DS . "application" . DS . "views" . DS . $view . "View.php") ;

            if($name == "") {
                $name = $view ;
            }

            $viewName = $view."View" ;
            $this->view[$name] = new $viewName() ;


        } else {
            throw new Exception('View not found') ;
        }
    }

    public function loadModel($model, $name = "") {
        if(file_exists(ROOT . DS . "application" . DS . "models" . DS . $model ."Model.php")) {
            require_once(ROOT . DS . "application" . DS . "models" . DS . $model . "Model.php") ;

            if($name == "") {
                $name = $model ;
            }

            $modelName = $model."Model" ;
            $this->model[$name] = new $modelName() ;


        } else {
            throw new Exception('View not found') ;
        }
    }

}
